package com.lepu.app.fun.index.activity;

import java.io.File;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.app.utils.MyNetUtil;
import com.app.utils.ObserverConst;
import com.app.utils.PlaySoundXfUtil;
import com.app.utils.SdLocal;
import com.app.utils.ZipUtil;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.AsyncRequest;
import com.core.lib.core.HttpRequest;
import com.core.lib.utils.ObserverManager;
import com.core.lib.utils.main.UIHelper;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;
import com.lepu.pasm.R;
import android.view.ViewGroup.MarginLayoutParams;

public class IndexKnowDetailActivity extends BaseFragmentActivity implements
		OnTopbarNewLeftLayoutListener, AsyncRequest {
	
	private WebView webview;
	private ImageView helpImage;
	private TextView helpText;
	private ImageView readImage;
	private PlaySoundXfUtil playSound;
	private String mArticleId;
	private String readContent = "";
	private String name = "";
	private MediaPlayer mediaPlayer = null;
	public TextView textview1;
	public TextView textview2;
	public String viewCount;
	public String favourCount;
	
	private boolean isFinish = false;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.index_know_detail_activity);

		init();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		playSound.stopSound();
		
		if(mediaPlayer != null){
			mediaPlayer.stop();
		}
		
	}

	/**
	 * 添加页面动画，需要重写这个方法，
	 */
	@Override
	public void onBackPressed() {
		finish(true);
	}

	@Override
	public void onTopbarLeftLayoutSelected() {
		finish(true);
	}

	/**
	 * 初始化方法
	 */
	@SuppressWarnings("unchecked")
	@SuppressLint({ "SetJavaScriptEnabled", "JavascriptInterface" })
	private void init() {
		// topbar
		CustomTopBarNew topbar = (CustomTopBarNew) findViewById(R.id.topbar);
		topbar.setTopbarTitle("术后天天知");
		topbar.setonTopbarNewLeftLayoutListener(this);

		textview1 = (TextView) findViewById(R.id.textview1);
		textview2 = (TextView) findViewById(R.id.textview2);
		
		playSound = new PlaySoundXfUtil(IndexKnowDetailActivity.this);

		Bundle data = getIntent().getExtras();
		String url = "";
		if(data != null && data.size() > 0)
		{
			mArticleId = data.getString("articleId");
			url = data.getString("url");
			viewCount = data.getString("viewCount");
			favourCount = data.getString("favourCount");
		}else{
			return;
		}

		if(viewCount == null){
			textview1.setVisibility(View.GONE);
		}else{
			textview1.setText("阅读  "+viewCount);
		}
		
		if(favourCount == null){
			textview2.setVisibility(View.GONE);
		}else{
			textview2.setText("点赞  "+favourCount);
		}
		
		if(!TextUtils.isEmpty(url))
		{
//			if(url.endsWith("\\t"))
//			{
//				StringBuffer sb = new StringBuffer(url);
//				sb.deleteCharAt(url.length()-1);
//				url = sb.toString().trim();
//			}
			url = url.replaceAll("\\s*", ""); 
		}
		
		String nameZip = url.split("/")[url.split("/").length-1];
		name = nameZip.split("\\.")[0];
		
		webview = (WebView) this.findViewById(R.id.webview);
		webview.setOnLongClickListener(new View.OnLongClickListener() {

			@Override
			public boolean onLongClick(View v) {
				// 禁止长按复制文本
				android.util.Log.d("DDD", "DDD");
				return true;
			}
		});

		WebSettings settings = webview.getSettings();
		settings.setJavaScriptEnabled(true);
		settings.setLoadWithOverviewMode(true);
		webview.setWebChromeClient(new WebChromeClient());
		webview.setWebViewClient(new CustomWebClient());
		webview.getSettings().setJavaScriptEnabled(true);
		webview.addJavascriptInterface(new InJavaScriptLocalObj(), "local_obj");
		
		//webview.loadUrl(path);
		
		helpImage = (ImageView) findViewById(R.id.help_image);
		helpText = (TextView) findViewById(R.id.help_text);
		readImage = (ImageView) findViewById(R.id.read_image);
		
		helpImage.setOnClickListener(viewClick);
		readImage.setOnClickListener(viewClick);
		
		String htmlPath = SdLocal.getCacheDataSHTTZFolder(IndexKnowDetailActivity.this)+"/"+name+".html";
		File file = new File(htmlPath);
		
		//如果已经下载直接加载
		if(file.exists()){
			webview.loadUrl("file://"+htmlPath);
		}else{
			//下载文件
			new MyTask(url, name).execute();
		}
		
		String soundPath = SdLocal.getCacheDataSHTTZFolder(IndexKnowDetailActivity.this)+"/"+name+".amr";
		File fileSound = new File(soundPath);
		if(fileSound.exists()){
			Uri uri = Uri.parse(soundPath);
		    mediaPlayer = MediaPlayer.create(getApplicationContext(), uri);
		    mediaPlayer.setOnCompletionListener(soundClick);
		}
		
	}
	
	View.OnClickListener viewClick = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.help_image:
				if(helpImage.isSelected()){
					
				}else{
					requestAddHelp();
				}
				
				break;
		
			case R.id.read_image:
				if(mediaPlayer != null){
					if(!readImage.isSelected()){  //点击朗读
							mediaPlayer.start();
							readImage.setSelected(true);
					}else{                        //暂停朗读
						if(!mediaPlayer.isPlaying()){
							mediaPlayer.stop();
							readImage.setSelected(false);
						}else{
							mediaPlayer.pause();
							readImage.setSelected(false);
						}
					}
				}else{
					if(isFinish){
						playSound.playSound(readContent, readImage);
					}
					
				}
				
				break;

			default:
				break;
			}
		}
	};
	
	OnCompletionListener soundClick = new OnCompletionListener() {
		
		@Override
		public void onCompletion(MediaPlayer arg0) {
			  readImage.setSelected(false);
//			  mediaPlayer.stop();
//			  mediaPlayer = null;
//			  String soundPath = SdLocal.getCacheDataSHTTZFolder(IndexKnowDetailActivity.this)+"/"+name+".amr";
//		   	  File fileSound = new File(soundPath);
//		   	  if(fileSound.exists()){
//		   			Uri uri = Uri.parse(soundPath);
//		   		    mediaPlayer = MediaPlayer.create(getApplicationContext(), uri);
//		   	  }
		}
	};
	
	/**
	 * help请求
	 */
	private void requestAddHelp() {
		MyNetUtil.getInstance().requestAddHelp(this, this,MyNetUtil.REQUEST_ADD_HELP, mArticleId, 2);
	}
	
	
    @SuppressWarnings("rawtypes")
	class MyTask extends AsyncTask {
    	String url;
    	String name;
        public MyTask( String url,  String name){
        	this.url = url;
        	this.name = name;
        }
    	
        @Override
        protected Object doInBackground(Object... params) {
        	//下载路径.zip
			String loadPath = SdLocal.getShuHouTianTianZhiPath(IndexKnowDetailActivity.this, name);
			boolean flag = HttpRequest.downloadFile(url, loadPath);
			if(flag){
				try {
					//解压
					ZipUtil.UnZipFolder(loadPath, SdLocal.getCacheDataSHTTZFolder(IndexKnowDetailActivity.this));
					return "success";
				} catch (Exception e) {
					e.printStackTrace();
					return "fail";
				}
			}else{
				return "fail";
			}
		
        }

        @Override
        protected void onPostExecute(Object result) {
            if (result.equals("success")) {
            	  //解压成功后获取文件夹目录下的html加载
            	  String htmlPath = "file://"+SdLocal.getCacheDataSHTTZFolder(IndexKnowDetailActivity.this)+"/"+name+".html";
            	  webview.loadUrl(htmlPath);
            	  
	        	  String soundPath = SdLocal.getCacheDataSHTTZFolder(IndexKnowDetailActivity.this)+"/"+name+".amr";
	        	  File fileSound = new File(soundPath);
	        	  if(fileSound.exists()){
	        			Uri uri = Uri.parse(soundPath);
	        		    mediaPlayer = MediaPlayer.create(getApplicationContext(), uri);
	        	  }
	        	  
            } else {
            	UIHelper.showToast(IndexKnowDetailActivity.this, "加载失败");
            }
        }
    }

	@Override
	public void RequestComplete(Object arg0, Object arg1) {
		if(arg0.equals(MyNetUtil.REQUEST_ADD_HELP)){
			helpImage.setSelected(true);
			helpText.setText("已赞");
			if(favourCount != null){
				textview2.setText("点赞  "+(Integer.valueOf(favourCount)+1));
			}
			UIHelper.showToast(IndexKnowDetailActivity.this, "点赞成功");
			ObserverManager.getInstance().notify(ObserverConst.NOTIFY_KNOW_UPDATE, null,"favour");
		}
	}
	
	@SuppressLint("HandlerLeak")
	public Handler mHandler = new Handler() {

		public void handleMessage(Message msg) {

			switch (msg.what) {
			case 1:
//				int top = (Integer) msg.obj;
//				RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
//	            layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
//	        	layoutParams.setMargins(0,top1,0,0);
//	        	textview.setLayoutParams(layoutParams);
//				setLayoutY(textview1, top);
	        	
				break;
			
			default:
				break;
			}
		};
	};
	

	@Override
	public void RequestError(Object arg0, int arg1, String arg2) {
		if(arg0.equals(MyNetUtil.REQUEST_ADD_HELP)){
		}
	}
	
	
	class CustomWebClient extends WebViewClient {

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			super.onPageStarted(view, url, favicon);
		}
		
		@Override
		public boolean shouldOverrideUrlLoading(WebView webView, String url) {
			
            return true;
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			//view.loadUrl("javascript:window.local_obj.showSource(document.getElementsByClassName(\"title\")[0].offsetHeight);");
			view.loadUrl("javascript:window.local_obj.showSource(document.documentElement.innerText);");
			super.onPageFinished(view, url);
			ObserverManager.getInstance().notify(ObserverConst.NOTIFY_KNOW_UPDATE, null,"view");
			if(viewCount != null){
				textview1.setText("阅读  "+(Integer.valueOf(viewCount)+1));
			}
		}
	}

    final class InJavaScriptLocalObj {
    	
    	@JavascriptInterface
        public void showSource(String html) {
        	
        	if(!isFinish){
        		isFinish = true;
        		readContent = html.replaceAll("\n", "").replaceAll(" ","");
        	}
        	
        }
    }
    
    public static void setLayoutY(View view,int y) 
    { 
			MarginLayoutParams margin=new MarginLayoutParams(view.getLayoutParams()); 
			//margin.setMargins(margin.leftMargin,y, margin.rightMargin, y+margin.height); 
			margin.setMargins(margin.leftMargin,y, margin.rightMargin, margin.height); 
			RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(margin); 
			view.setLayoutParams(layoutParams); 
    } 

}
